class Snake {
  container:HTMLElement;
  head:HTMLElement;
  bodies:HTMLCollection;
  constructor(){
    this.container = document.getElementById('snake')!
    this.head = this.container.querySelector('.head')!
    this.bodies = this.container.getElementsByTagName('div')
  }

  // 蛇头坐标
  get Hx():number{
    return this.head.offsetLeft
  }
  get Hy():number{
    return this.head.offsetTop
  }

  // 移动蛇头
  set Hx(value:number){
    if(this.Hx === value) return
    // 检查是否撞墙
    this.isCrush(value)
    // 检查是否撞击蛇身
    this.isCrushSelf(this.Hx,this.Hy)
     // 移动蛇身
    this.moveBody()
    // 移动蛇头
    this.head.style.left = value + 'px'
  }
  set Hy(value:number){
    if(this.Hy === value) return
    // 检查是否撞墙
    this.isCrush(value)
    // 检查是否撞击蛇身
    this.isCrushSelf(this.Hx,this.Hy)
    // 移动蛇身
    this.moveBody()
    // 移动蛇头
    this.head.style.top = value + 'px'
  }
  
  // 增加身长
  addBody():void{
    const div = document.createElement('div')
    this.container.append(div)
  }

  // 蛇身移动
  moveBody():void{
    if(this.bodies.length === 1) return
    for (let i = this.bodies.length - 1; i > 0; i--) {
      // 蛇身移动其实就是后面一格的位置变为前面一格蛇身的位置
      // 获取前面一格蛇身的位置
      let x = (this.bodies[i - 1] as HTMLElement).offsetLeft;
      let y = (this.bodies[i - 1] as HTMLElement).offsetTop;
      // 赋值
      (this.bodies[i] as HTMLElement).style.left = x + 'px';
      (this.bodies[i] as HTMLElement).style.top = y + 'px';
    }
  }

  // 是否撞墙
  isCrush(value:number):void{
    if(value < 0 || value > 290) {
      throw Error('游戏结束')
    }
  }

   // 是否撞击蛇身
  isCrushSelf(x:number,y:number):void{
    for (let i = this.bodies.length - 1; i > 0; i--) {
      let left = (this.bodies[i] as HTMLElement).offsetLeft;
      let top = (this.bodies[i] as HTMLElement).offsetTop;
      if(x === left && y === top){
        throw new Error('游戏结束')
      }
    }
  }
}

export default Snake;